var $doc, $jsonDataList = {},
	policyid = '',
	userid = '',
	$dia;
$(function() {
	$doc = $(document);
	//从地址栏中获取openid并将id赋值给input[type=hiden] userid
	policyid = getURLParam('policyid').replace(/#/, '');
	userid = getURLParam('userid').replace(/#/, '');
	getPolicyData();
	$doc.on('focus', '.data-list', function(e) {
		var tar = $(e.target),
			inter = tar.attr('inter');
		if (inter == 'beneficiary') {
			createBeneficiaryDialog({
				title: tar.attr('title'),
				render: tar.attr('id')
			}, $jsonDataList[inter]);
		} else {
			createListDialog({
				title: tar.attr('title'),
				render: tar.attr('id')
			}, $jsonDataList[inter]);
		}
		tar.blur();
	});
	$doc.on('touchend click', '#btnSave', function(e) {
		layer.msg('正在提交数据')
			//添加数据
		var p = $('#formPolicy').serialize();
		var dp = {
			inter: 'policyadd'
		};
		$('#formPolicy').find('input,textarea').each(function(idx, el) {
			dp[el.name] = (el.attributes['data-value'] && el.attributes['data-value'].value) || el.value;
		});
		getDataInterFace(dp, function(rData) {
			if (rData && rData.success == 1) {
				layer.msg('保存成功!');
				window.location.href = "policylistwx.html?userid=" + userid;
			} else {
				layer.msg('保存失败!');
			}
		});
		return _stopDefaultEvent(e);
	});
	$doc.on('submit', 'form', function(e) {
		return _stopDefaultEvent(e);
	});
	$doc.on('scroll mousewheel', '.ui-dialog-bd ul', function(e) {
		$('.ui-dialog-bd ul li').removeClass('active');
		$(e.target).addClass('active');
	});
	$doc.on('touchend', '.ui-icon-close', function(e) {
		var tar = $(e.target),
			prev = tar.prev();
		prev.val('').removeAttr('data-value');
		return _stopDefaultEvent(e); //防止事件冒泡
	});
	$doc.on('touchend', '.data-list-dialog .ui-dialog-bd ul li', function(e) {
		$('.ui-dialog-bd ul li').removeClass('active');
		$(e.target).addClass('active');
		//如果弹窗下面有按钮，则需要点击按钮才能确认选择事件，否则直接回填
		var btns = $('.data-list-dialog .ui-btn-group').find('button');
		if (btns.length == 0) { //直接回填
			backfill();
			$dia.remove();
		}
		return _stopDefaultEvent(e);
	});
	//增加受益人
	$doc.on('touchend', '.l-btn-ben', function(e) {
		//判断不能超过8个元素
		var $ic = $('.beneficiary-dialog .content ul'),
			len = $ic.find('li').length;
		if (len > 6) {
			alert('已经超过最大数量了!');
		} else {
			var strHTML = ['<li>', '<input type="text" value="" />', '<input type="number" value="' + (len == 6 ? 20 : 16) + '" />', '<em>%</em>', '<label class="btnDelete">删除</label>', '</li>'];
			$(strHTML.join('')).insertBefore($(e.target).parent());
		}
		return _stopDefaultEvent(e);
	});
	//删除行元素
	$doc.on('touchend', '.btnDelete', function(e) {
		var tar = $(e.target);
		tar.parent().remove();
	});
	//保存按钮事件
	$doc.on('touchend', '.beneficiary-dialog #dialogButton', function(e) {
		//先校验比例值是否分配合适,合计等于100,否则提示
		var $ic = $('.beneficiary-dialog .content'),
			$linum = $ic.find('li input:nth-child(2)'),
			$liname = $ic.find('li input:first-child'),
			number = 0,
			snum = [],
			name = [];
		$linum.each(function(idx, el) {
			snum.push($(el).val());
			number += parseInt($(el).val());
		});
		$liname.each(function(idx, el) {
			name.push($(el).val());
		});
		if (number != 100) {
			alert('您分配的比例值不正确!');
		} else {
			//如果合适，将数据回填到元素中，并将元素填写到数据库中
			getDataInterFace({
				inter: 'addbeneficiary',
				userid: userid,
				beneficiary: name.join(',')
			}, function(rData) {});
			//将结果回填到元素中
			var strVal = [];
			for (var i = 0, l = name.length; i < l; i++) {
				strVal.push(name[i] + '(' + snum[i] + '%)');
			}
			$('#beneficiary').val(strVal.join(' '));
			//同时关闭窗口
			$('.beneficiary-dialog').hide();
		}
		return _stopDefaultEvent(e);
	});
});
/**
 * 获取翻译字段信息
 */
function getTransEl() {
	$('.data-list').each(function(idx) {
		var tar = $(this),
			inter = tar.attr('inter');
		if (inter == 'age') {
			var ages = [];
			for (var i = 1; i <= 100; i++) {
				ages.push({
					id: i,
					text: i
				});
			}
			$jsonDataList[inter] = ages;
		} else if (inter == 'isdividends') {
			$jsonDataList[inter] = [{
				id: '1',
				text: '有'
			}, {
				id: '0',
				text: '无'
			}];
			resetInputValue(inter);
		} else if (inter == 'iperson') {
			$jsonDataList[inter] = [{
				id: '本人',
				text: '本人'
			}, {
				id: '妻子',
				text: '妻子'
			}, {
				id: '丈夫',
				text: '丈夫'
			}, {
				id: '子女',
				text: '子女'
			}];
		} else {
			getDataInterFace({
				inter: inter,
				userid: userid
			}, function(rData) {
				$jsonDataList[inter] = rData;
				resetInputValue(inter);
			});
		}
	});
}
/**
 * 重置获取到的值
 */
function resetInputValue(inter) {
	var d = $jsonDataList[inter],
		$ic = $('#formPolicy *[inter=' + inter + ']'),
		slv = $ic.attr('data-value');
	d.forEach(function(v) {
		if (parseInt(v.id) == parseInt(slv)) {
			$ic.val(v.text);
			return ;
		}
	});
}
/**
 * 获取保单数据
 */
function getPolicyData() {
	getDataInterFace({
		inter: 'getpolicybyid',
		policyid: policyid
	}, function(rData) {
		if (rData) {
			var policy = rData[0];
			console.log('详细数据', policy);
			//回填数据
			$('input,textarea').each(function(idx, el) {
				var tar = $(el),
					inter = tar.attr('inter'),
					name = tar.attr('name');
				tar.val(policy[name]);
				if (inter) { //如果有接口调用，就去接口数据中加载对应的数据
					tar.attr({
						'data-value': policy[name]
					});
				}
			});
		}
		getTransEl();
	});
}
/**
 * 创建选项选择框
 * @param {Object} config 配置项，主要是标题
 * @param {Object} data 选择数据列表
 */
function createListDialog(config, data) {
	var content = [],
		slv = $('#' + config.render).attr('data-value'),
		l = data.length;
	//数据项小于8个就不显示确定按钮
	for (var i = 0; i < l; i++) {
		content.push('<li data-value="' + data[i].id + '" class="' + (slv == data[i].id ? 'active' : '') + '">' + data[i].text + '</li>');
	}
	$dia = $.dialog({
		title: config.title,
		cn: 'data-list-dialog',
		render: config.render || '',
		content: '<ul>' + content.join('') + '</ul>',
		button: l < 8 ? [] : ["确认", "取消"]
	});
	//确定按钮事件
	$doc.on('touchend click', '.ui-btn-group #dialogButton0', function(e) {
		//获取当前选中项并返回值
		backfill();
		$dia.remove();
		return _stopDefaultEvent(e); //防止事件冒泡
	});
	//取消按钮事件
	$doc.on('touchend click', '.ui-btn-group #dialogButton1', function(e) {
		$dia.remove();
		return _stopDefaultEvent(e); //防止事件冒泡
	});

}
/**
 * 创建受益人弹窗
 * @param {Object} config 配置项，主要是标题
 * @param {Object} data 选择数据列表
 */
function createBeneficiaryDialog(config, data) {
	var content = [],
		l = data.length,
		v = parseInt(100 / (l == 0 ? 1 : l)),
		lv = (100 - l * v) + v; //最后一个的值

	for (var i = 0; i < l; i++) {
		content.push('<li><input type="text" value="' + data[i]['beneficiary'] + '" /><input type="number" value="' + (i == l - 1 ? lv : v) + '" /><em>%</em><label class="btnDelete">删除</label></li>');
	}
	content.push('<li class="li-btn"><label class="l-btn-ben">增加受益人</label></li>');
	var $ic = $('.beneficiary-dialog').show(),
		dialog = $ic.find('.ui-dialog-bd');
	dialog.find('h4').html(config.title);
	dialog.find('.content').html('<ul>' + content.join('') + '</ul>');
	var $cnt = $ic.find('.ui-dialog-cnt'),
		cntH = $cnt.height();
	$cnt.css({
		'margin-top': h ? (h - cntH) / 2 : '40%'
	});
}
/**
 * 回填事件,将弹窗选中元素回填到元素中
 */
function backfill() {
	var sel = $('.ui-dialog-bd ul li.active'),
		ren = $('.data-list-dialog').attr('render'),
		v = sel.attr('data-value'),
		dv = parseInt(v);
	$("#" + ren).attr({
		'data-value': isNaN(dv) ? v : dv
	}).val(sel.html());
}